<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function DoublyLinkedList() {
        this.head = null;
        this.tail = null;
        this.length = 0;

        function Node(data) {
          this.data = data;
          this.prev = null;
          this.next = null;
        }

        //方法
        //1.append()
        DoublyLinkedList.prototype.append = function (element) {
          // 1.根据元素创建节点
          var newnode = new Node(element);
          //是否为空
          if (this.length == 0) {
            this.head = newnode;
            this.tail = newnode;
          } else {
            this.tail.next = newnode;
            newnode.prev = this.tail;
            this.tail = newnode;
          }
          this.length++;
        };

        //2.toString()
        DoublyLinkedList.prototype.toString = function () {
          var current = this.head;
          var res = "";
          while (current) {
            res += current.data + "----";
            current = current.next;
          }
          return res;
        };

        //3.insert()
        DoublyLinkedList.prototype.insert = function (position, element) {
          // 1.判断越界的问题
          if (position < 0 || position > this.length) return false;

          // 2.创建新的节点
          var newNode = new Node(element);

          // 3.判断插入的位置
          if (position === 0) {
            // 在第一个位置插入数据
            // 判断链表是否为空
            if (this.head == null) {
              this.head = newNode;
              this.tail = newNode;
            } else {
              this.head.prev = newNode;
              newNode.next = this.head;
              this.head = newNode;
            }
          } else if (position === this.length) {
            // 插入到最后的情况
            // 思考: 这种情况是否需要判断链表为空的情况呢? 答案是不需要, 为什么?
            this.tail.next = newNode;
            newNode.prev = this.tail;
            this.tail = newNode;
          } else {
            // 在中间位置插入数据
            // 定义属性
            var index = 0;
            var current = this.head;
            var previous = null;

            // 查找正确的位置
            while (index++ < position) {
              previous = current;
              current = current.next;
            }

            // 交换节点的指向顺序
            newNode.next = current;
            newNode.prev = previous;
            current.prev = newNode;
            previous.next = newNode;
          }

          // 4.length+1
          this.length++;

          return true;
        };
      }

        //4.get()
         

      var item = new DoublyLinkedList();
      item.append("1111");
      item.append("11111");
      item.append("111111");
      item.insert(1,'222')
      console.log(item.toString());
    </script>
  </body>
</html>
